<template>
  <div class="p-2">
    <div class="viewBox">
      <el-form ref="testFormRef" :model="form" :rules="rules" label-width="120px">
        <el-tabs v-model="activeTab">
          <el-tab-pane label="基本信息" name="information">
            <el-form-item label="实验名称" prop="testName">
              <el-input v-model="form.testName" placeholder="请输入实验名称" />
            </el-form-item>
            <el-form-item label="学科" prop="subject">
              <!-- <el-input v-model="form.subject" placeholder="请输入学科" /> -->
              <el-select v-model="form.subject" clearable placeholder="请选择学科">
                <el-option v-for="dict in subjectOptions" :key="dict.id" :label="dict.subjectName" :value="dict.id"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="年级" prop="grade">
              <!-- <el-input v-model="form.grade" placeholder="请输入年级" /> -->
              <el-select v-model="form.grade" clearable placeholder="请选择年级">
                <el-option v-for="dict in sys_grade" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
              </el-select>
            </el-form-item>
            <div class="dialog-footer">
              <el-button type="primary" @click="activeTab = 'principle'">下一步</el-button>
              <el-button :loading="buttonLoading" type="primary" @click="submitForm">暂 存</el-button>
            </div>
          </el-tab-pane>
          <el-tab-pane label="实验原理" name="principle">
            <el-form-item :prop="activeTab = 'principle'?principle:''" label-width="0">
              <editor v-model="form.principle" :min-height="120" placeholder="请输入内容" />
            </el-form-item>
            <div class="dialog-footer">
              <el-button type="primary" @click="activeTab = 'step'">下一步</el-button>
              <el-button :loading="buttonLoading" type="primary" @click="submitForm">暂 存</el-button>
              <el-button @click="activeTab = 'information'">返回</el-button>
            </div>
          </el-tab-pane>
          <el-tab-pane label="实验步骤" name="step">
            <div v-if="type == 2">
              <!-- v-loading="loading" -->
              <el-table  :data="tableList">
                <!-- <el-table-column label="序号" align="center" prop="id" /> -->
                <el-table-column label="序号"  type="index" align="center" width="50" />
                <el-table-column label="步骤阶段" align="center" prop="stage" />
                <el-table-column label="步骤名称" align="center" prop="stepName" >
                </el-table-column>
              
                <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
                  <template #default="scope">
                    <el-button type="text" size="small"  @click="handleView(scope.row)" >查看</el-button>
                  </template>
                </el-table-column>
              </el-table>
              <pagination
                  v-show="total>0"
                  :total="total"
                  v-model:page="queryParams.pageNum"
                  v-model:limit="queryParams.pageSize"
                  @pagination="getList"
              />
            </div>
            <div v-else>
              <div v-for="(step, index) in formSteps" :key="index" class="step-item">
                <div class="left-box">
                  <el-form-item :label="`步骤阶段 ${index + 1}`" :prop="`stepList.${index}.stage`">
                    <!-- <el-input v-model="step.stage" placeholder="请输入步骤阶段" disabled /> -->
                    <div class="desc">{{ step.stage }}</div>
                  </el-form-item>
                  <el-form-item :label="`步骤名称 ${index + 1}`" :prop="`stepList.${index}.stepName`">
                    <!-- <el-input v-model="step.stepName" placeholder="请输入步骤名称" disabled /> -->
                    <div class="desc">{{ step.stepName }}</div>
                  </el-form-item>
                  <el-form-item :label="`步骤细节 ${index + 1}`" :prop="`stepList.${index}.detail`">
                    <!-- <el-input v-model="step.detail"  type="textarea" placeholder="请输入内容" disabled /> -->
                    <div v-html="step.detail" class="desc htbox"></div>
                  </el-form-item>
                </div>
                <div class="right-btn">
                  <el-button type="primary" @click="showAddStepDialog" v-if="index == formSteps.length-1">添加步骤</el-button>
                  <el-button type="primary" @click="editStep(index)">编辑步骤</el-button>
                  <el-button type="danger" @click="removeStep(index)">删除步骤</el-button>
                </div>
              </div>
              <!-- 添加步骤按钮，只有在没有步骤时才显示 有步骤只在最后一步显示 -->
              <el-button type="primary" v-if="!formSteps || formSteps.length < 1" @click="showAddStepDialog">添加步骤</el-button>

              <div class="dialog-footer">
                <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
                <el-button @click="cancel">返回</el-button>
              </div>
            </div>
            
          </el-tab-pane>
        </el-tabs>
      </el-form>
    </div>
    <!-- 添加/编辑步骤对话框 -->
    <el-dialog :title="dialogTitle" v-model="dialogVisible" width="800px">
      <el-form :model="currentStep" :rules="stepRules" ref="stepFormRef">
        <el-form-item label="步骤阶段" prop="stage">
          <el-input v-model="currentStep.stage" placeholder="请输入步骤阶段" :disabled="type == 2"></el-input>
        </el-form-item>
        <el-form-item label="步骤名称" prop="stepName">
          <el-input v-model="currentStep.stepName" placeholder="请输入步骤名称" :disabled="type == 2"></el-input>
        </el-form-item>
        <el-form-item label="步骤细节" prop="detail">
          <editor v-model="currentStep.detail" :min-height="120" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <div class="dialog-footer" v-if="type != 2">
        <el-button type="primary" @click="handleStepSubmit">确 定</el-button>
        <el-button @click="dialogVisible = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script setup name="Test" lang="ts">
import { listTest, getTest, delTest, addTest, updateTest } from '@/api/core/test';
import {listTestStep} from '@/api/testStep'
// import { StepDetail,TestVO, TestQuery, TestForm } from '@/api/core/test/types';
import { TestVO,StepVO, TestQuery, TestForm } from '@/api/core/test/types';
//学科
import { useSubjectList } from '@/composables/useSubjectList';
const { subjectOptions, fetchSubjectList } = useSubjectList();

const route = useRoute();
const router = useRouter();
const { proxy } = getCurrentInstance() as ComponentInternalInstance;

const { sys_notice_type, sys_period, sys_grade } = toRefs<any>(proxy?.useDict('sys_notice_type', 'sys_period', 'sys_grade'));
const activeTab = ref('information');
const formSteps = reactive<Array<{ stage: string; stepName: string; detail: string }>>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const tableList = ref<StepVO[]>([]);


const queryFormRef = ref<ElFormInstance>();
const testFormRef = ref<ElFormInstance>();
const stepFormRef = ref<ElFormInstance>();

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

const type = ref<string | number>();

const formId = ref('');
const title = ref('');

const initFormData: TestForm = {
  id: undefined,
  testName: undefined,
  subject: undefined,
  grade: undefined,
  principle: undefined,
  stepList: []
};
const data = reactive<PageData<TestForm, TestQuery>>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    // testName: undefined,
    // subject: undefined,
    // grade: undefined,
    // principle: undefined,
    // stepList: [],
    params: {}
  },
  rules: {
    testName: [{ required: true, message: '实验名称不能为空', trigger: 'blur' }],
    subject: [{ required: true, message: '学科不能为空', trigger: 'blur' }],
    grade: [{ required: true, message: '年级不能为空', trigger: 'blur' }],
    principle: [{ required: true, message: '实验原理不能为空', trigger: 'blur' }]
  }
});

const { queryParams, form, rules } = toRefs(data);

const currentStepIndex = ref<number | null>(null);
const currentStep = reactive<{ stage: string; stepName: string; detail: string }>({ stage: '', stepName: '', detail: '' });
const dialogTitle = ref<string>('');
const dialogVisible = ref<boolean>(false);
const stepRules = reactive({
  stage: [{ required: true, message: '步骤阶段不能为空', trigger: 'blur' }],
  stepName: [{ required: true, message: '步骤名称不能为空', trigger: 'blur' }],
  detail: [{ required: true, message: '步骤细节不能为空', trigger: 'blur' }]
});

//查看实验步骤
// const handleView = (index: number,row) => {
//   dialogTitle.value = '查看步骤';
//   currentStepIndex.value = index;
//   Object.assign(currentStep, formSteps[index]);
//   dialogVisible.value = true;
// };
const handleView = (row: StepVO) => {
  dialogTitle.value = '查看步骤';
  // currentStep.value = row;
  Object.assign(currentStep, row);
  console.log('查看',row,currentStep.value);
  dialogVisible.value = true;
};

const showAddStepDialog = () => {
  dialogTitle.value = '添加步骤';
  currentStepIndex.value = null;
  Object.assign(currentStep, { stage: '', stepName: '', detail: '' });
  dialogVisible.value = true;
};

const editStep = (index: number) => {
  dialogTitle.value = '编辑步骤';
  currentStepIndex.value = index;
  Object.assign(currentStep, formSteps[index]);
  dialogVisible.value = true;
};

const handleStepSubmit = () => {
  stepFormRef.value?.validate((valid: boolean) => {
    if (valid) {
      if (currentStepIndex.value !== null) {
        formSteps[currentStepIndex.value] = { ...currentStep };
      } else {
        formSteps.push({ ...currentStep });
      }
      dialogVisible.value = false;
    }
  });
};

const removeStep = (index: number) => {
  formSteps.splice(index, 1);
};

const cancel = () => {
  reset();
  router.go(-1);
};

const reset = () => {
  form.value = { ...initFormData };
  testFormRef.value?.resetFields();
};

const submitForm = () => {
  testFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      try {
        form.value.stepList = formSteps.map((step) => ({ ...step }));
        if (form.value.id) {
          await updateTest(form.value);
          ElMessage.success('修改成功');
        } else {
          await addTest(form.value);
          ElMessage.success('添加成功');
        }
        router.go(-1);
      } catch (error) {
        ElMessage.error('操作失败');
      } finally {
        buttonLoading.value = false;
      }
    }else{
      console.log('error')
    }
  });
};

(async () => {
  formId.value = route.query && (route.query.id as string);
  type.value = route.query && (route.query.type as string);
  if (formId.value) {
    const res = await getTest(formId.value);
    if(res.data.subject != undefined && res.data.subject != null){
      res.data.subject = +res.data.subject;
    }
    Object.assign(form.value, res.data);
    formSteps.length = 0;
    if (res.data.stepList.length > 0) {
      res.data.stepList.forEach((step) => {
        formSteps.push({ stage: step.stage, stepName: step.stepName, detail: step.detail });
      });
    }
    title.value = '编辑';
    if(type.value == 2){
      //分页获取实验步骤
      // loading.value = true;
      // loading.value = false;
      getList();
    }
  } else {
    title.value = '新增';
  }
  fetchSubjectList();
})();

const getList = async () => {
  const list = await listTestStep(queryParams.value);
  tableList.value = list.rows;
  total.value = list.total;
  console.log('分页获取实验步骤',list);
}

</script>
<style lang="scss" scoped>
.viewBox {
  margin: 15px 15px 80px 15px;
  .title-item {
    display: flex;
    align-items: center;
    height: 24px;
    line-height: 24px;
    font-size: 20px;
    margin: 30px 0 20px;
    span {
      display: inline-block;
      margin: 0 5px;
    }
    .line-box {
      width: 4px;
      height: 24px;
      background: #05afea;
    }
  }
  .topTit {
    margin-top: 10px;
  }
  .el-form-item--default {
    margin: 15px 30px;
  }
  :deep(.el-textarea__inner) {
    width: 300px !important;
  }
}
.el-input {
  width: 300px;
}
.el-select {
  width: 300px;
}
.dialog-footer {
  margin-top: 100px;
  text-align: center;
}

.step-item {
  display: flex;
  align-items: baseline;
  .left-box {
    min-width: 600px;
    .el-form-item--default .el-form-item__content {
      width: 400px;
    }
    .htbox {
    }
  }
  .right-btn {
    width: 400px;
  }
}
</style>
